package com.yf.boot.ability.qiniu.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.processing.OperationManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import com.yf.boot.base.api.exception.ServiceException;
import com.yf.boot.ability.qiniu.service.QiniuService;
import com.yf.boot.ability.upload.utils.OssUtils;
import com.yf.modules.sys.config.dto.CfgUploadQiniuDTO;
import com.yf.modules.sys.config.service.CfgUploadQiniuService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @author bool
 */
@Log4j2
@Service
public class QiniuServiceImpl implements QiniuService {

    @Autowired
    private CfgUploadQiniuService cfgUploadQiniuService;

    @Override
    public String convertVideo(String url) {

        log.error("++++++++++start-oss-convert11:"+url);

        // 查找配置
        CfgUploadQiniuDTO conf = cfgUploadQiniuService.find();

        // bucket
        String bucket = conf.getBucket();

        // 替换访问域名则是正确的bucket路径
        String key = url.replace(conf.getUrl(), "");

        // 新文件名
        String newKey = key + ".mp4";

        //设置账号的AK,SK
        Auth auth = Auth.create(conf.getAccessKeyId(), conf.getAccessKeySecret());

        Zone z = Zone.zone0();
        Configuration c = new Configuration(z);

        //新建一个OperationManager对象
        OperationManager operater = new OperationManager(auth, c);

        // 设置转封装
        String fops = "avthumb/mp4/vcodec/copy/acodec/copy";

        // 对转码文件进行重命名
        String urlbase64 = UrlSafeBase64.encodeToString(bucket + ":" + newKey);
        String pfops = fops + "|saveas/" + urlbase64;
        //设置pipeline参数
        StringMap params = new StringMap().putWhen("force", 1, true).putNotEmpty("pipeline", null);
        try {
            String persistid = operater.pfop(bucket, key, pfops, params);
            log.error("+++++转换结果：{}", persistid);
            return conf.getUrl() + newKey;
        } catch (QiniuException e) {
            throw new ServiceException(e.getMessage());
        }
    }

    @Override
    public String upload(String localFile) {

        // 查找配置
        CfgUploadQiniuDTO conf = cfgUploadQiniuService.find();

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = conf.getAccessKeyId();
        String secretKey = conf.getAccessKeySecret();
        String bucket = conf.getBucket();
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = OssUtils.processPath(localFile);;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(localFile, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);

            //返回结果
            return conf.getUrl() + putRet.key;

        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }

            return null;
        }
    }
}
